package com.laolang.shop.modules.im.util;

import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import com.laolang.shop.modules.im.config.ImProp;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

/**
 * @author khlbat
 * @version 1.0
 * @date 2020/11/2 2:23
 */
@Slf4j
@AllArgsConstructor
@Component
public class ImUrlGen {

    private final ImProp imProp;

    private final StringRedisTemplate stringRedisTemplate;

    private static final String USERSIG_KEY = "im_usersig_key";

    private static final String URL_TPL = "{url}/{servicename_command}?sdkappid={appId}&identifier={username}&usersig={usersig}&random={random}&contenttype=json";

    public String genUrl(String servicenameWithCommand) {
        Map<String, Object> map = new HashMap<>();
        map.put("url", imProp.getBaseUrl());
        map.put("servicename_command", servicenameWithCommand);
        map.put("appId", imProp.getSdkappid());
        map.put("username", imProp.getIdentifier());
        map.put("usersig", imProp.getUserSig());
        map.put("random", getRandom());
        return StrUtil.format(URL_TPL, map);
    }

    private long getRandom() {
        return RandomUtil.randomLong(1, 4294967294L);
    }
}
